package com.jihox.abookpro;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.R;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.Country;
import com.jihox.abookpro.domain.DeliveryInfo;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.helper.AddressUtils;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.DialogListener;
import com.jihox.abookpro.util.NetStatus;
import com.jihox.abookpro.util.RegexChk;
import com.jihox.abookpro.view.AddAndSubText;
import com.jihox.abookpro.view.AddressPickerDialog;
import com.jihox.abookpro.view.JHProgressDialog;

public class OrderActivity extends BaseActivity {

	private EditText etRecipient = null;
	private EditText etMobile = null;
	private EditText etAddress = null;
//	private EditText etPostCode = null;
	//private EditText etEmail = null;
	private TextView txtAmount = null;
	private TextView tvProvince = null;
    private EditText etProvince = null;
    private EditText etRemarks=null;
    
	private DeliveryInfo deliveryInfo = null;

	private float price = 0;
	private int quantity = 1;
	private BookProject project = null;
	private String zipFileName = "";
	public static final String PREFS_NAME = "DeliveryInfoPrefsFile1";
	private JHProgressDialog pd;
    private Country country = null;
	private ContentObserver imagesObserver;
    private String coverBitmapPath = "";
    private ImageView ivProduct = null;   
    private static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟  
	private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟  
	private Order order;
	
	private String oldWorksn;
	private String from = null;
	
	private String cstToken;
//	private static final String SHAREDPREFERENCES_CUSTOMERINFO = "CUSTOMER_TOKEN";
	private String templateName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);

		// AndroidBug5497Workaround.assistActivity(this);

		Intent intent = this.getIntent();
		templateName = intent.getStringExtra("templateName");
		Bundle bundle = intent.getExtras();
		MyApplication application = MyApplication.getInstance();
		project = application.getBookProject();
	    coverBitmapPath = bundle.getString("coverBitmap");
	    oldWorksn = bundle.getString("OldWorksn", null);
	    from = bundle.getString("From",null);
		txtAmount = (TextView) findViewById(R.id.txtAmount);
		
		//price = bundle.getFloat("Price");
		txtAmount.setText(getResources().getString(R.string.T_Price_uint));
		
		ivProduct =(ImageView) findViewById(R.id.ivProduct);
		Bitmap coverBitmap = BitmapFactory.decodeFile(coverBitmapPath);
		ivProduct.setImageBitmap(coverBitmap);
		AddAndSubText text = (AddAndSubText) findViewById(R.id.samrtText);
		text.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable arg0) {
				quantity = Integer.parseInt(arg0.toString());
				
				//float 和double 都是非精确计算，所以会有微些的差别
				//采用四舍五入的办法 保留两位				
				BigDecimal b = new BigDecimal(price * quantity);
				txtAmount.setText(  b.setScale(2,BigDecimal.ROUND_HALF_UP).floatValue()+ getResources().getString(R.string.T_Price_uint));
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated mehod stub
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
			}
		});

		getDeliveryInfo();
		etRecipient = (EditText) findViewById(R.id.etRecipient);
		etRecipient.setText(deliveryInfo.getConsignee());
		etMobile = (EditText) findViewById(R.id.etMobile);
		etMobile.setText(deliveryInfo.getMobile());
		etAddress = (EditText) findViewById(R.id.etAddress);
		etAddress.setText(deliveryInfo.getAddress());
//		etPostCode = (EditText) findViewById(R.id.etPostCode);
//		etPostCode.setText(deliveryInfo.getPostCode());

		etRemarks=(EditText) findViewById(R.id.etRemark);
		etRemarks.setText(deliveryInfo.getRemark());

		tvProvince = (TextView) findViewById(R.id.tvProvince);
		if (deliveryInfo.getCountyCode().isEmpty() || deliveryInfo.getCityCode().isEmpty() || deliveryInfo.getProvinceCode().isEmpty()){
			tvProvince.setText(getResources().getString(R.string.T_Please_select)+getResources().getString(R.string.T_Dot));
		}else{
			String address = deliveryInfo.getProvince() + " " + deliveryInfo.getCity()+ " "+ deliveryInfo.getCounty();
			if (address.length()>16){
				address = address.substring(0,16) + getResources().getString(R.string.T_Dot);
			}
			tvProvince.setText(address);
		}
		
		tvProvince.setSingleLine(true);
		tvProvince.setEllipsize(TextUtils.TruncateAt.END);

		tvProvince.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (country == null){
					pd = JHProgressDialog.show(OrderActivity.this, null,
							getResources().getString(R.string.T_Loading_short));
						new Thread(addressRunnable).start();
				}else{
					// 初始化一个自定义的Dialog
					Dialog dialog = new AddressPickerDialog(OrderActivity.this,
							dialogListener,deliveryInfo.getProvince(),deliveryInfo.getCity(),deliveryInfo.getCounty(),country);
					dialog.setTitle(getResources().getString(R.string.T_Please_select)+getResources().getString(R.string.T_Area_text));
					dialog.show();
					WindowManager m = getWindowManager();
					Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
					Window dialogWindow = dialog.getWindow();
					WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
					//p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6
					p.width = (int) (d.getWidth()); // 宽度设置为屏幕的0.65
					p.x = 0;
					p.y = 0;
					dialogWindow.setAttributes(p);
				}
			}

		});
		
		etProvince = (EditText)findViewById(R.id.etProvince);
		etProvince.setInputType(InputType.TYPE_NULL);
		etProvince.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus){
					if (country == null){
						pd = JHProgressDialog.show(OrderActivity.this, null,
								getResources().getString(R.string.T_Loading_short));
							new Thread(addressRunnable).start();
					}else{
						// 初始化一个自定义的Dialog
						Dialog dialog = new AddressPickerDialog(OrderActivity.this,
								dialogListener,deliveryInfo.getProvince(),deliveryInfo.getCity(),deliveryInfo.getCounty(),country);
						dialog.setTitle(getResources().getString(R.string.T_Please_select)+getResources().getString(R.string.T_Area_text));
						
						dialog.show();
						WindowManager m = getWindowManager();
						Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
						Window dialogWindow = dialog.getWindow();
						WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
						//p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6
						p.width = (int) (d.getWidth()); // 宽度设置为屏幕的0.65
						p.x = 0;
						p.y = 0;
						dialogWindow.setAttributes(p);
					}
				}
				
			}
		});

		Button submitButton = (Button) findViewById(R.id.btnSubmit);
		submitButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
	
				if (NetStatus.getNetState(getApplicationContext()) == NetStatus.NET_NOT_PREPARE) {
					showToast(getResources().getString(R.string.T_Order_fail_Net));
					return;
				}
				
				//价格没有获取
				if(price <= 0 ){
					showNoPriceDialog();
					return;
				}
				if (valid()) {
					//查询用户cstToken,以便判断是否已经登录过
					cstToken = MyApplication.getInstance().getCstToken();
					String useidcode = MyApplication.getInstance().getUserId();
					if(cstToken.length()>0 && useidcode.length()>0){
						pd = JHProgressDialog.show(OrderActivity.this, null,
								getResources().getString(R.string.T_Submitting_Order)+getResources().getString(R.string.T_Wait)+getResources().getString(R.string.T_Dot));
							saveDeliveryInfo();

							new Thread(runnable).start();

					}else{
							Toast.makeText(OrderActivity.this, "请先登录", Toast.LENGTH_LONG).show();
							Intent intent = new Intent(OrderActivity.this,LoginActivity.class);
							startActivity(intent);
					}
						
					
				}
	
			}
		});

		Button returnButton = (Button) findViewById(R.id.btnReturn);
		returnButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(AccountDetailActivity.class.getName().equals(from)){
					finish();
					return;
				}
				
				Intent intent = new Intent();
				intent.setClass(OrderActivity.this, CurlActivity.class);  
				OrderActivity.this.startActivity(intent); 
				finish();
			}
		});
		imagesObserver = new ImagesObserver(new Handler()){
			@Override
			public void onChange(boolean selfChange) {
				if(!checkSelectedList()){
					Intent intent = new Intent();    
					if (order!=null){
						intent.putExtra("templateName", order.getTemplateName());
					}
					intent.setClass(OrderActivity.this, GallerySelectActivity.class);   
					OrderActivity.this.startActivity(intent);
					finish();
				}
			}
		};
		this.getContentResolver().registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, imagesObserver); 
		//get the price 
		getPrice();
	}

	private void showNoPriceDialog(){
		final Dialog dialog = new Dialog(OrderActivity.this, R.style.JHDialog);
        //设置它的ContentView
        dialog.setContentView(R.layout.dialog_general);
        Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
        Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
        TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);
        
        buttonOK.setBackgroundResource(R.drawable.delete_style);
        buttonCancel.setBackgroundResource(R.drawable.grey_style);
        buttonOK.setText(R.string.T_Ok);
        buttonCancel.setText(R.string.T_Cancel);
        
        dialogTitle.setText(R.string.T_NO_Price_Title);
        dialogMessage.setText(R.string.T_Get_Price_Again);
        
        buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				getPrice(); 
			}
		});
        buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
        
        dialog.show();
	}
	private void getPrice(){
		pd = JHProgressDialog.show(OrderActivity.this, null,
				getResources().getString(R.string.T_Loading_short));
		new Thread(getPriceRunnable).start();
	}
	
	private Runnable getPriceRunnable = new Runnable() {
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			HttpGet httpGet = new HttpGet(
					ConfigProperties.getProductPriceUrl().replace("{}",project.getBook().getProduct().getPid()));
			UserHelper helper = new UserHelper();
			httpGet.setHeader("username", helper.getUserName());
			httpGet.setHeader("password", helper.getPassword());
			TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        	String imei = tm.getDeviceId();
			httpGet.setHeader("deviceId", imei);
			Message msg = new Message();
			Bundle data = new Bundle();
			try {

				HttpResponse response = httpclient.execute(httpGet);
				HttpEntity resEntity = response.getEntity();

				if (resEntity != null) {

					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
					data.putString("value", res);
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPrice));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPrice));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPrice));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPrice));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPrice));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				getPricehandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};
	
	private Handler getPricehandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.dismiss();

			Bundle data = msg.getData();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				showToast(error);
				return;
			}

			String val = data.getString("value");
			try {
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (isSuccess) {

					float tempPrice = (float) result.getDouble("price");
					Log.d("OrderActivity", tempPrice + "");
					price = tempPrice;
					txtAmount.setText(price + getResources().getString(R.string.T_Price_uint));
				} else {
					showToast(getResources().getString(R.string.T_NoNet_NoPrice));
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showToast(getResources().getString(R.string.T_NoNet_NoPrice));
			} catch(Exception e){
				showToast(e.getMessage());
			}
		}
	};
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			
			if(AccountDetailActivity.class.getName().equals(from)){
				finish();
				return false;
			}
			
			Intent intent = new Intent();
			intent.setClass(OrderActivity.this, CurlActivity.class);  
			Bundle mBundle = new Bundle();  
			mBundle.putString("From", from);
			intent.putExtras(mBundle);  
			OrderActivity.this.startActivity(intent); 
			finish();
		}
		return false;
	}

	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		getContentResolver().unregisterContentObserver(imagesObserver);
		BitmapDrawable bd = (BitmapDrawable)ivProduct.getDrawable();
		ivProduct.setImageResource(0);

		bd.setCallback(null);
		if (bd.getBitmap()!=null){
			bd.getBitmap().recycle();
		}

		super.onDestroy();
	}
	
	DialogListener dialogListener = new DialogListener() {

		@Override
		public void setAddress(String provinceCode, String province,
				String cityCode, String city, String countyCode, String county) {
			deliveryInfo.setProvinceCode(provinceCode);
			deliveryInfo.setCityCode(cityCode);
			deliveryInfo.setCountyCode(countyCode);
			deliveryInfo.setProvince(province);
			deliveryInfo.setCity(city);
			deliveryInfo.setCounty(county);
			String address = province+ " " + city+ " "+ county;
			if (address.length()>16){
				address = address.substring(0,16) + getResources().getString(R.string.T_Dot);
			}
			tvProvince.setText(address);
			etAddress.requestFocus();
			
			InputMethodManager imm = (InputMethodManager) getApplicationContext()
					  .getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		}
	};
	
	Runnable addressRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				if (country==null){
					AddressUtils addressUtils = new AddressUtils();
					InputStream inputStream = getAssets().open("country_province_city_county.xml");
					country = addressUtils.getCountry(inputStream);
					deliveryInfo.setCountryCode(country.getCode());
				}
			} catch (IOException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
			addressHandler.sendEmptyMessage(0);
		}
	};
	
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			String url = ConfigProperties.getOrderServerUrl();
			TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        	String imei = tm.getDeviceId();
			HttpPost httpPost = new HttpPost(url);
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());
			httpPost.setHeader("deviceId", imei);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("country", deliveryInfo.getCountryCode()));
			params.add(new BasicNameValuePair("province", deliveryInfo.getProvinceCode()));
			params.add(new BasicNameValuePair("city", deliveryInfo.getCityCode()));
			params.add(new BasicNameValuePair("district", deliveryInfo.getCountyCode()));
			params.add(new BasicNameValuePair("zipcode", deliveryInfo.getPostCode()));
			params.add(new BasicNameValuePair("email", deliveryInfo.getEmail()));
			params.add(new BasicNameValuePair("addressDetail", deliveryInfo.getAddress()));
			params.add(new BasicNameValuePair("consignee", deliveryInfo.getConsignee()));
			params.add(new BasicNameValuePair("mobile", deliveryInfo.getMobile()));
			params.add(new BasicNameValuePair("remark", deliveryInfo.getRemark()));
			params.add(new BasicNameValuePair("orderitemvos[0].orderitemprice",
					String.valueOf(price*quantity)));
			params.add(new BasicNameValuePair("orderitemvos[0].number", String.valueOf(quantity)));
			String productId = project.getBook().getProduct().getPid();
			params.add(new BasicNameValuePair("orderitemvos[0].productid",
					productId));
			zipFileName = productId + ".zip";
			params.add(new BasicNameValuePair("orderitemvos[0].workfilename",
					zipFileName));
			String tif[] = templateName.split("_");
			String templateid = tif[tif.length-2];
			params.add(new BasicNameValuePair("orderitemvos[0].templateid",
					templateid));
			params.add(new BasicNameValuePair("appversion","appVersion:\\n"+getVersion() + "phone Info : \\n" + getPhoneInfo()));
			
			params.add(new BasicNameValuePair("cstToken",
					cstToken));
			
			order = new Order();
			order.setDeliveryInfo(deliveryInfo);
			order.setPrice(price);
			order.setNumber(String.valueOf(quantity));
			order.setProductId(String.valueOf(productId));
			order.setTemplateName(templateName);
			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				
				BasicHttpParams httpParams = new BasicHttpParams();  
			    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
				HttpClient httpclient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpclient.execute(httpPost);
				String result = EntityUtils.toString(httpResponse.getEntity());
				
				Log.i("msg", result);
				
				data.putString("value", result);
				msg.setData(data);
				handler.sendMessage(msg);

			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_Order_fail_TimeOut));
				msg.setData(data);
				handler.sendMessage(msg);
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_Order_fail_TimeOut));
				msg.setData(data);
				handler.sendMessage(msg);
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_Order_fail_TimeOut));
				msg.setData(data);
				handler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	};

	Handler addressHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.dismiss();
			// 初始化一个自定义的Dialog
			Dialog dialog = new AddressPickerDialog(OrderActivity.this,
					dialogListener,deliveryInfo.getProvince(),deliveryInfo.getCity(),deliveryInfo.getCounty(),country);
			dialog.setTitle(getResources().getString(R.string.T_Please_select)+getResources().getString(R.string.T_Area_text));
			
			dialog.show();
			WindowManager m = getWindowManager();
			Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
			Window dialogWindow = dialog.getWindow();
			WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
			//p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6
			p.width = (int) (d.getWidth()); // 宽度设置为屏幕的0.65
			p.x = 0;
			p.y = 0;
			dialogWindow.setAttributes(p);
			
		}
	};
	
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			Bundle data = msg.getData();
			String error = data.getString("Error");

			if (error != null && !error.isEmpty()) {
				showToast(error);
				pd.dismiss();
				return;
			}

			String val = data.getString("value");
			try {
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (isSuccess) {
					float shippingfee = (float) result.getDouble("shippingfee");
					order.setCreatedtime(result.getString("createdtime"));
					String orderDeliveryCycle = result
							.getString("expecteddeliverydate");
					String orderCode = result.getString("orderid");
					JSONArray worklist = result.getJSONArray("workidlist");
					String worksn = "";
					for (int i = 0; i < worklist.length(); i++) {
						JSONObject orderItem = ((JSONObject) worklist.opt(i));
						if (orderItem.getString("filename").equals(zipFileName)) {
							worksn = orderItem.getString("workid");
						}
					}
					
					order.setOrderId(orderCode);
					order.setBookProject(project);
					Bitmap coverBitmap = BitmapFactory.decodeFile(coverBitmapPath);
					order.setThumbnail(coverBitmap);
					order.setOrderStatus(Order.ORDER_STATUS_NOT_PAY);
					order.setWorksn(worksn);
					MyApplication application = MyApplication.getInstance();
					application.setWorksn(worksn);
					order.setOrderDeliveryCycle(orderDeliveryCycle);
					OrderDAO dao = new OrderDAO(OrderActivity.this);
					dao.addOrderInfo(order);
					
					order.setShippingfee(shippingfee);
					
					order.setOldWorksn(oldWorksn);
					order.setThumbnail(null);
					pd.dismiss();
					showToast(getResources().getString(R.string.T_Order_Success));
					Intent intent = new Intent();
					intent.setClass(OrderActivity.this, PayActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("OrderInfo", order);
					intent.putExtras(bundle);
					OrderActivity.this.startActivity(intent);
					pd.dismiss();
					finish();
				} else {
					String result_msg = result.getString("msg");
					pd.dismiss();
					if("Token is time out !".equals(result_msg)){
						Toast.makeText(OrderActivity.this, "用户信息已过期,请重新登录", Toast.LENGTH_LONG).show();
						Intent intent = new Intent(OrderActivity.this,LoginActivity.class);
						intent.putExtra("comefrom", "orderactivity");
						startActivity(intent);
					}else{
						Log.i("msg_order_res", result_msg);
						showToast(getResources().getString(R.string.T_Order_fail_Try_Later));
					}
				}

			} catch (JSONException e) {
				pd.dismiss();
				e.printStackTrace();
				showToast(getResources().getString(R.string.T_Order_fail_Try_Later));
			}

		}
	};
	
	
	private void saveDeliveryInfo() {

		SharedPreferences sp = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		// 存入数据
		Editor editor = sp.edit();
		editor.putString("Address", deliveryInfo.getAddress());
		editor.putString("City", deliveryInfo.getCity());
		editor.putString("Country", deliveryInfo.getCountryCode());
		editor.putString("County", deliveryInfo.getCounty());
		editor.putString("Province", deliveryInfo.getProvince());
		editor.putString("CityCode", deliveryInfo.getCityCode());
		editor.putString("CountyCode", deliveryInfo.getCountyCode());
		editor.putString("ProvinceCode", deliveryInfo.getProvinceCode());
		editor.putString("Email", deliveryInfo.getEmail());
		editor.putString("Mobile", deliveryInfo.getMobile());
		editor.putString("PostCode", deliveryInfo.getPostCode());
		editor.putString("Recipient", deliveryInfo.getConsignee());
		editor.putString("Remark", deliveryInfo.getRemark());
		editor.commit();
	}

	private void getDeliveryInfo() {
		deliveryInfo = new DeliveryInfo();
		SharedPreferences sp = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

		deliveryInfo.setAddress(sp.getString("Address", ""));
		deliveryInfo.setCity(sp.getString("City", ""));
		deliveryInfo.setCounty(sp.getString("County", ""));
		deliveryInfo.setProvince(sp.getString("Province", ""));
		deliveryInfo.setCityCode(sp.getString("CityCode", ""));
		deliveryInfo.setCountyCode(sp.getString("CountyCode", ""));
		deliveryInfo.setProvinceCode(sp.getString("ProvinceCode", ""));
		deliveryInfo.setEmail(sp.getString("Email", ""));
		deliveryInfo.setMobile(sp.getString("Mobile", ""));
		deliveryInfo.setPostCode(sp.getString("PostCode", ""));
		deliveryInfo.setConsignee(sp.getString("Recipient", ""));
		deliveryInfo.setCountryCode(sp.getString("Country", ""));
		deliveryInfo.setRemark(sp.getString("Remark", ""));
	}

	private boolean valid() {
		if (this.etRecipient.getText().toString().equals("")) {
			showToast(getResources().getString(R.string.T_Receiver_Needed));
			this.etRecipient.requestFocus();
			return false;
		}
		deliveryInfo.setConsignee(this.etRecipient.getText().toString());

		String cellPhone = this.etMobile.getText().toString().trim();
		if (cellPhone.equals("")) {
			showToast(getResources().getString(R.string.T_Phone_Needed));
			this.etMobile.requestFocus();
			return false;
		}
		if (!RegexChk.checkCellPhone(cellPhone)) {
			showToast(getResources().getString(R.string.T_Phone_Format_Error));
			this.etMobile.requestFocus();
			return false;
		}

		deliveryInfo.setMobile(cellPhone);

		 if (this.deliveryInfo.getProvinceCode().isEmpty()
				 ||this.deliveryInfo.getCityCode().isEmpty()
				 ||this.deliveryInfo.getCountyCode().isEmpty()) {
			 showToast(getResources().getString(R.string.T_Please_select)+getResources().getString(R.string.T_Area_text));
			 this.tvProvince.requestFocus();
			 return false;
		 }

		if (this.etAddress.getText().toString().equals("")) {
			showToast(getResources().getString(R.string.T_Address_Needed));
			this.etAddress.requestFocus();
			return false;
		}
		deliveryInfo.setAddress(this.etAddress.getText().toString());

//		String email = this.etEmail.getText().toString().trim();
//		if (email.equals("")) {
//			showToast(getResources().getString(R.string.T_Email_Needed));
//			this.etEmail.requestFocus();
//			return false;
//		}
//		if (!RegexChk.checkEmail(email)) {
//			showToast(getResources().getString(R.string.T_Email_Format_Error));
//			this.etEmail.requestFocus();
//			return false;
//		}
//
//		deliveryInfo.setEmail(this.etEmail.getText().toString());

//		String postCode = this.etPostCode.getText().toString().trim();
//		if (!postCode.isEmpty()) {
//			if (!RegexChk.checkPostcode(postCode)) {
//				showToast(getResources().getString(R.string.T_PostCode_Format_Error));
//				this.etPostCode.requestFocus();
//				return false;
//			}
//			deliveryInfo.setPostCode(postCode);
//		}
		
		deliveryInfo.setRemark(this.etRemarks.getText().toString().trim());
		return true;
	}
	
}
